package easier.data.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 保存类到文件
 *
 * @param <T> 类型
 */
public class ObjectStore< T extends Serializable > {

    /**
     * @param file 类文件
     * @param e    类
     * @param <E>  数据类型
     *
     * @throws Exception 异常
     */
    public static < E extends Serializable > void write( File file, E e ) throws Exception {

        new ObjectStore< E >( file ).writeObject( e );
    }

    /**
     * @param file 类文件
     * @param <E>  数据类型
     *
     * @return 类
     *
     * @throws Exception 异常
     */
    public static < E extends Serializable > E read( File file ) throws Exception {

        return new ObjectStore< E >( file ).readObject();
    }

    /**
     * 保存类的文件
     */
    private final File mFile;

    /**
     * @param file 保存文件
     */
    public ObjectStore( File file ) {

        mFile = file;
    }

    /**
     * @param t 保存类文件
     *
     * @throws Exception 异常
     */
    public void writeObject( T t ) throws Exception {

        FileOutputStream outputStream = new FileOutputStream( mFile );
        ObjectOutputStream oo = new ObjectOutputStream( outputStream );
        oo.writeObject( t );
        oo.flush();
        oo.close();
    }

    /**
     * @return 读取类文件
     *
     * @throws Exception 异常
     */
    @SuppressWarnings( "unchecked" )
    public T readObject() throws Exception {

        FileInputStream inputStream = new FileInputStream( mFile );
        ObjectInputStream oi = new ObjectInputStream( inputStream );
        T o = (T) oi.readObject();
        oi.close();
        return o;
    }
}
